package tech.veedo.munchkin.verifications.backend.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import tech.veedo.munchkin.beans.backend.Auditor;
import tech.veedo.munchkin.constants.Type;
import tech.veedo.munchkin.constants.Operation;
import tech.veedo.munchkin.verifications.backend.AuditorVerify;

import java.util.List;

@Slf4j
@Service
public class AuditorVerifyImpl implements AuditorVerify {

    @Override
    public boolean verify(Operation operation, Auditor auditor) {
        switch (operation) {
            case ADD:
                return addVerify(auditor);
            case UPDATE:
                return updateVerify(auditor);
            default:
                return true;
        }
    }

    @Override
    public boolean verifyBatch(Operation operation, List<Auditor> auditors) {
        auditorsNotNullWhenVerifyBatch(auditors);
        for (Auditor auditor : auditors) {
            verify(operation, auditor);
        }
        return true;
    }

    private boolean addVerify(Auditor auditor) {
        nodeIDNotNull(auditor.getNodeID());
        typeNotNull(auditor.getType());
        InfoNotNullUnderType(auditor.getType(), auditor.getPsnID(), auditor.getPostCode());
        return true;
    }

    private boolean updateVerify(Auditor auditor) {
        idNotNull(auditor.getId());
        return true;
    }

    private void idNotNull(Long id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new NullPointerException("审核人员id为空");
        }
    }

    private void auditorsNotNullWhenVerifyBatch(List<Auditor> auditors) {
        if (CollectionUtils.isEmpty(auditors)) {
            throw new NullPointerException("审核人列表为空");
        }
    }

    private void nodeIDNotNull(Long nodeID) {
        if (ObjectUtils.isEmpty(nodeID)) {
            throw new NullPointerException("审核人挂接的审核节点id为空");
        }
    }

    private void typeNotNull(Type type) {
        if (ObjectUtils.isEmpty(type)) {
            throw new NullPointerException("审核人类型为空");
        }
    }

    private void InfoNotNullUnderType(Type type, String psnID, String postCode) {
        if (type == Type.PERSON) {
            if (StringUtils.isBlank(psnID)) {
                throw new NullPointerException("当类型是person时，psnId不能为空.");
            }
            //            case POST:
//                if (StringUtils.isBlank(postCode)) {
//                    throw new NullPointerException("when the type is POST, the postCode is null.");
//                }
//                break;
        } else {
            throw new IllegalArgumentException("审核人类型可能为空.");
        }
    }

}
